#include "rayleigh_groundlayer.h"
#include <QDebug>
#include <math.h>
#include <QTimer>

RayleighGroundLayer::RayleighGroundLayer(QString layerName,
					 double hBottom,
					 double hTop,
					 QObject *parent) :
    RayleighAtmosphere(layerName, hBottom, hTop, parent),
    m_groundAlbedo(0.3)
{
    connect(this, SIGNAL(groundScatUp(QByteArray)),
	    this, SLOT(recvScatInUp(QByteArray)));

    //caculation procedure for Lamb-ground-approximation,
    //caculate downard irridiance, then the up-intensity is got.
    //Must change procedure for BRDF or PBRDF model!!!
    connect(this, SIGNAL(gotDownIrradiance(double)),
	    this, SLOT(recvDownIrridance()));
}


void RayleighGroundLayer::recvDownIrridance()
{
	QTimer::singleShot(10, this, SLOT(groundScatResponse()));
}

//caculation procedure for Lamb-ground-approximation,
//caculate downard irridiance, then the up-intensity is got.
//BRDF mode is not realized, 2011-11-4
#include <stdio.h>
void RayleighGroundLayer::groundScatResponse()
{
	qDebug() << "RayleighGroundLayer::groundScatResponse(). m_currentIrradiance/m_downIrradiance: " << m_currentIrradiance/m_downIrradiance;
	if(m_currentIrradiance < m_downIrradiance*0.0001){
		qDebug() << "Interate caculation over, current step's down irradiance at ground is:" << m_currentIrradiance <<"\n\n\n*************************************\n\n\n\n";
		printf("\a");
		exit(0);
	}

	//change directon
	m_currentDir = UP;

	double intensity = m_currentIrradiance * m_groundAlbedo;

	QByteArray light;
	QDataStream strm(&light, QIODevice::ReadWrite);
	for(int i = 0; i < N_PI/2; i++){
		for(int j = 0; j < N_PI * 2; j++){
			strm << intensity
			     << (double) 0.0 << (double) 0.0;
//			qDebug() << "groundScatResponse()"
//				 << i << j << intensity << m_currentIrridiance;
		}
	}

	emit(groundScatUp(light));
}

void RayleighGroundLayer::setGroundAlbedo(double albedo)
{
	m_groundAlbedo = albedo;
	qDebug() << "Ground albedo set to:" << m_groundAlbedo;
}

double RayleighGroundLayer::getCurrentGroundAlbedo()
{
	return m_groundAlbedo;
}
